package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mockingjay
 * @date 2023/4/29 - 23:47
 */
public class MockKingJayApplication {

    private Class configClass;

    //单例池
    private ConcurrentHashMap<String,Object> singletonObjectsMap=new ConcurrentHashMap<>();
    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionObjectsMap=new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList=new ArrayList<>();

    public MockKingJayApplication(Class configClass){
        this.configClass=configClass;

        //1.解析配置类
        scan(configClass);

        // 2.找到单例bean放到单例池中
        for(Map.Entry<String,BeanDefinition> entry:beanDefinitionObjectsMap.entrySet()){
            String beanName=entry.getKey();
            BeanDefinition beanDefinition=entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                Object bean=createBean(beanName,beanDefinition);
                singletonObjectsMap.put(beanName,bean);
            }
        }
    }

    public Object createBean(String beanName,BeanDefinition beanDefinition){

        Class clazz = beanDefinition.getClazz();
        try {
            Object o = clazz.getDeclaredConstructor().newInstance();

            //依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {
                if(declaredField.isAnnotationPresent(AutoWired.class)){
                    Object bean=getBean(declaredField.getName());
                    if(bean==null){
                        return new NullPointerException();
                    }
                    declaredField.setAccessible(true);
                    declaredField.set(o,bean);
                }
            }
            //aware 回调
            if(o instanceof BeanNameAware){
                ((BeanNameAware) o).setBeanName(beanName);
            }
            //初始化前调用
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                beanPostProcessor.postProcessBeforeInitialization(o,beanName);
            }

            //初始化
            if(o instanceof InitializingBean){
                try {
                    ((InitializingBean) o).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //初始化后调用
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                beanPostProcessor.postProcessAfterInitialization(o,beanName);
            }

            return o;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    private void scan(Class configClass) {
        //ComponentScan注解-->扫描路径-->扫描-->beanDefinition-->beanDefinitionObjectsMap
        //判断是否有ComponentScan注解
        ComponentScan componentScan=(ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        //扫描路径
        String path=componentScan.value();
        //扫描
        //类加载器
        //1.bootstrap-->jre/-lib  2.ext-->jre/ext/lib  3.app-->classpath
        ClassLoader classLoader=MockKingJayApplication.class.getClassLoader();
        URL resource = classLoader.getResource(path.replace(".","/"));
        File file=new File(resource.getFile());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for (File f : files) {

                String fileName=f.getAbsolutePath();
                if(fileName.endsWith(".class")){
                    String packageName=fileName.substring(fileName.indexOf("com"),fileName.indexOf(".class")).
                            replace("\\" ,".");
                    Class<?> clazz = null;
                    try {
                        clazz = classLoader.loadClass(packageName);
                        if(clazz.isAnnotationPresent(Component.class)){

                            //如果是beanPostProcessor(判断是否实现了该接口)
                            if(BeanPostProcessor.class.isAssignableFrom(clazz)){
                                BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }

                            //表示当前的类是一个bean
                            //解析bean，判断当前bean是单例bean，还是prototype bean
                            BeanDefinition beanDefinition=new BeanDefinition();

                            Component ComponentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beanName=ComponentAnnotation.value();

                            if(clazz.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation=clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            }else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinition.setClazz(clazz);
                            beanDefinitionObjectsMap.put(beanName,beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String beanName){
        if (beanDefinitionObjectsMap.containsKey(beanName)){
            BeanDefinition beanDefinition=beanDefinitionObjectsMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){
                Object o=singletonObjectsMap.get(beanName);
                return o;
            }else {
                //创建bean对象(不是单例)
                Object bean= createBean(beanName,beanDefinition);
                return bean;
            }
        }else{
            //不存在对应的bean
            throw new NullPointerException();
        }
    }
}
